<template>
  <xr-create :loading="loading" :title="title" @close="close" @save="saveClick">
    <create-sections
      :title="$t('crm.components.ba116206bd6f09070bb2f172f4a86ee6')">
      <el-form
        ref="crmForm"
        :model="fieldForm"
        :rules="fieldRules"
        :validate-on-rule-change="false"
        class="wk-form"
        label-position="top">
        <wk-form-items
          v-for="(children, index) in fieldList"
          :key="index"
          :field-from="fieldForm"
          :field-list="children"
          @change="formChange">
          <template slot-scope="{ data }">
            <crm-relative-cell
              v-if="data && data.formType == 'customer'"
              :value="fieldForm[data.field]"
              :disabled="data.disabled"
              data-type="customer"
              @value-change="otherChange($event, data)"
            />
          </template>
        </wk-form-items>
      </el-form>
    </create-sections>
  </xr-create>
</template>

<script>
import {
  crmCustomerSaveAddressAPI,
  crmCustomerUpdateAddressAPI
} from '@/api/crm/customer'

import XrCreate from '@/components/XrCreate'
import CreateSections from '@/components/CreateSections'
import WkFormItems from '@/components/NewCom/WkForm/WkFormItems'
import {
  CrmRelativeCell
} from '@/components/CreateCom'

import CustomFieldsMixin from '@/mixins/CustomFields'

export default {
  // 新建编辑
  name: 'RelativeAddressCreate',

  components: {
    XrCreate,
    CreateSections,
    CrmRelativeCell,
    WkFormItems
  },
  mixins: [CustomFieldsMixin],
  props: {
    phone: String,
    action: {
      type: Object,
      default: () => {
        return {
          type: 'save',
          id: '',
          data: {}
        }
      }
    }
  },

  data() {
    return {
      loading: false,
      fieldList: [],
      fieldForm: {},
      fieldRules: {}
    }
  },

  computed: {
    title() {
      return this.action.type === 'update' ? this.$t('crm.components.a587cbfca571c13e89ac34e28862ba38') : this.$t('crm.components.d0e49ee0ef66ab747d24bbebb6c42545')
    }
  },

  watch: {
    action: {
      handler() {
        this.getField()
      },
      deep: true
    }
  },

  created() {
    this.getField()
  },

  mounted() {},

  beforeDestroy() {},

  methods: {
    /**
     * 获取数据
     */
    getField() {
      const detailData = this.action.type == 'update' ? this.action.rowData : null
      this.fieldList = [
        [{
          fieldName: 'addressType',
          field: 'addressType',
          name: this.$t('crm.components.dbfe18b7d31b4c415f7f5743f6609430'),
          formType: 'select',
          isNull: 1,
          fieldType: 1,
          inputTips: '',
          setting: [
            { label: this.$t('crm.components.ccf32f30fb66f933bb2e864e6203581f'), value: 1 },
            { label: this.$t('crm.components.e1a01142ac65f0a76b76cc4f8f0c53b1'), value: 2 },
            { label: this.$t('crm.components.1c94d4410910a835b7cbf8af87edcbde'), value: 3 },
            { label: this.$t('crm.components.df1e65e2410a4a9af64b6f8a775e49c4'), value: 4 },
            { label: this.$t('crm.components.f0c67ae405e165394e2eb6865532f2ae'), value: 5 },
            { label: this.$t('crm.components.c9450a5e7fc536daba0d03d356ff58dd'), value: 6 }
          ],
          stylePercent: 50,
          value: detailData ? detailData.addressType : ''
        },
        {
          fieldName: 'postalCode',
          field: 'postalCode',
          name: this.$t('crm.components.80f31c6f98b5ca2ceedf954917ca52b8'),
          formType: 'text',
          isNull: 0,
          fieldType: 1,
          inputTips: '',
          setting: [],
          stylePercent: 50,
          value: detailData ? detailData.postalCode : ''
        }],
        [{
          fieldName: 'contactsName',
          field: 'contactsName',
          name: this.$t('crm.components.5ccc319067aef0449c59cfb804ebaf5c'),
          formType: 'text',
          isNull: 0,
          fieldType: 1,
          inputTips: '',
          setting: [],
          stylePercent: 50,
          value: detailData ? detailData.contactsName : ''
        },
        {
          fieldName: 'telephone',
          field: 'telephone',
          name: this.$t('crm.components.b39cf043636dd91efd812dd3b254928b'),
          formType: 'mobile',
          isNull: 0,
          fieldType: 1,
          inputTips: '',
          setting: [],
          stylePercent: 50,
          value: detailData ? detailData.telephone : ''
        }],
        [{
          fieldName: 'address',
          field: 'address',
          name: this.$t('crm.components.a3b0b97258295a7936eb92042b791f90'),
          // formType: 'position',
          formType: 'text',
          isNull: 0,
          fieldType: 1,
          inputTips: '',
          setting: [],
          stylePercent: 100,
          value: detailData ? detailData.address : ''
        },
        {
          fieldName: 'remark',
          field: 'remark',
          name: this.$t('crm.components.28b937e4bcd2706ce150a82e5e8898d0'),
          formType: 'textarea',
          isNull: 0,
          fieldType: 1,
          inputTips: '',
          setting: [],
          stylePercent: 50,
          value: detailData ? detailData.remark : ''
        }]
      ]
      this.fieldList.forEach(item => {
        item.forEach(subItem => {
          this.$set(this.fieldForm, subItem.fieldName, subItem.value)
          this.$set(this.fieldRules, subItem.fieldName, this.getRules(subItem))
        })
      })
    },

    /**
     * 保存
     */
    saveClick() {
      this.loading = true
      const crmForm = this.$refs.crmForm
      crmForm.validate(valid => {
        if (valid) {
          const params = this.fieldForm
          this.submiteParams(params)
        } else {
          this.loading = false
          // 提示第一个error
          this.getFormErrorMessage(crmForm)
          return false
        }
      })
    },

    /**
     * 提交上传
     */
    submiteParams(params) {
      let request = crmCustomerSaveAddressAPI
      params.customerId = this.action.detail.customerId
      if (this.action.type == 'update') {
        params.addressId = this.action.rowData.addressId
        request = crmCustomerUpdateAddressAPI
      }

      // 相关添加时候的多余提交信息
      if (
        this.action.relativeData &&
        Object.keys(this.action.relativeData).length
      ) {
        params = { ...params, ...this.action.relativeData }
      }
      request(params)
        .then(res => {
          this.loading = false

          this.$message.success(
            this.action.type == 'update' ? this.$t('crm.components.5c2f66c6f948b61e67b1b2a07f2c2f9c') : this.$t('crm.components.dd32c3dc56405abcc880d3f1f6635507')
          )

          this.close()

          // 保存成功
          this.$emit('save-success', {
            type: 'address'
          })
        })
        .catch(() => {
          this.loading = false
        })
    },

    /**
     * 验证唯一
     */
    UniquePromise({ field, value }) {
      return this.getUniquePromise(field, value, this.action)
    },

    /**
     * change
     */
    formChange(field, index, value, valueList) {
      if ([
        'select',
        'checkbox'
      ].includes(field.formType) &&
          field.remark === 'options_type' &&
          field.optionsData) {
        const { fieldForm, fieldRules } = this.getFormContentByOptionsChange(this.fieldList, this.fieldForm)
        this.fieldForm = fieldForm
        this.fieldRules = fieldRules
      }
    },

    /**
     * 地址change
     */
    otherChange(data, field) {
      this.$set(this.fieldForm, field.field, data.value)
      this.$refs.crmForm.validateField(field.field)
    },

    /**
     * 关闭
     */
    close() {
      this.$emit('close')
    }
  }
}
</script>

<style lang="scss" scoped></style>
